using System;
using System.Collections.Generic;
using Gj.Galaxy.Logic;
using Gj.TapTap;
#if UNITY_IOS
using System.Runtime.InteropServices;
#endif
using UnityEngine;

namespace Gj
{
  public class SocialManager
  {
    //社交平台枚举

    public enum Platform : int
    {
      Token = 0,
      GameCenter = 1,
      Wechat = 2,
      Facebook = 3,
      GooglePlay = 4,
      Mi = 5,
      Huawei = 6,
      Uc = 7,
      TapCn = 8,
      TapIo = 9,
      Steam = 10,
    };

    public enum AuthType
    {
        _,
        // web的Oauth流程
        Oauth,
        // app的 Oauth流程
        AppOauth,
        // phone系统账号，服务端不鉴权
        AppOfflineOauth,
    }

    public interface PlatformAuth
    {
        void IsAuthorized(AuthDelegate callback);
        void Authorize(AuthDelegate callback);
        void Real(RealDelegate callback);
        void SubmitLeaderboard(string key, int value, LeaderboardDelegate callback);
        void AddAchievement(string key, int value, AchievementDelegate callback);
        bool CanLocalShare();
        void DirectShare(string title, string imagePath, string description, string targetUrl, string videoUrl, ShareDelegate callback);
        void Logout(LogoutDelegate callback);
    }

    public static Dictionary<Platform, AuthType> AuthTypePlatform = new Dictionary<Platform, AuthType>
    {
        {Platform.GameCenter, AuthType.AppOfflineOauth},
        {Platform.GooglePlay, AuthType.AppOfflineOauth},
        {Platform.Facebook, AuthType.AppOfflineOauth},
        {Platform.Wechat, AuthType.Oauth},
        {Platform.Mi, AuthType.Oauth},
        {Platform.Huawei, AuthType.AppOfflineOauth},
        {Platform.Uc, AuthType.AppOfflineOauth},
        {Platform.TapCn, AuthType.AppOfflineOauth},
        {Platform.TapIo, AuthType.AppOfflineOauth},
        {Platform.Steam, AuthType.Oauth},
    };
    
    public static Dictionary<Platform, string> ChannelPlatform = new Dictionary<Platform, string>
    {
        {Platform.GameCenter, "apple_game_center"},
        {Platform.GooglePlay, "google_game_play"},
        {Platform.Facebook, "facebook_app"},
        {Platform.Wechat, "wechat_app"},
        {Platform.Mi, "mi_game"},
        {Platform.Huawei, "huawei_app"},
        {Platform.Uc, "uc_game"},
        { Platform.TapCn, "tapcn_app"},
        { Platform.TapIo, "tapio_app"},
        { Platform.Steam, "steam_pc"},
        { Platform.Token, "token"}
    };
    
    public static Dictionary<Platform, string> DefinePlatform = new Dictionary<Platform, string>
    {
        {Platform.GameCenter, "apple_game_center"},
        {Platform.GooglePlay, "google_game_play"},
        {Platform.Facebook, "facebook"},
        {Platform.Wechat, "wechat"},
        {Platform.Mi, "mi"},
        {Platform.Huawei, "huawei"},
        {Platform.Uc, "uc"},
        { Platform.TapCn, "tapcn"},
        { Platform.TapIo, "tapio"},
        { Platform.Steam, "steam"},
        { Platform.Token, "token"}
    };

    // 本地系统安装
    public static Dictionary<string, Platform> LocalPlatform = new Dictionary<string, Platform>{
    {
        "apple_game_center", Platform.GameCenter
    },
    {
        "google_game_play", Platform.GooglePlay
    },
    {
        "steam", Platform.Steam
    },
    {
        "mi_game", Platform.Mi
    },
    {
        "huawei", Platform.Huawei
    },
    {
        "uc_game", Platform.Uc
    },
    {
        "tapcn", Platform.TapCn
    },
    {
        "tapio", Platform.TapIo
    },
    {
        "token", Platform.Token
    }
    };

    public static Dictionary<Platform, PlatformAuth> localPlatformAuth = new Dictionary<Platform, PlatformAuth>();

    public class Player
    {
        public Platform Platform;
        public Dictionary<string, string> message;
    }

    //成功状态码 
    //用于 授权回调 和 分享回调 的是非成功的判断
    public const int SUCCESS = 200;

    public static Player localPlayer;
    public static List<Platform> allow;

    public delegate void RegisterDelegate(Platform platform, bool isInstall, bool isShared, bool isLeaderboard, bool isAchievement, bool isReal);
    //授权回调
    public delegate void AuthDelegate(Platform platform, int stCode, Dictionary<string, string> message);

    public delegate void LogoutDelegate(Platform platform);

    public delegate void RealDelegate(Platform platform, int stCode, string errorMsg);

    //分享回调:注意 android 分享失败 没有 errorMsg
    public delegate void ShareDelegate(Platform platform, int stCode, string errorMsg);
    
    // 排行榜回调
    public delegate void LeaderboardDelegate(Platform platform, int stCode, string errorMsg);

    // 成就回调
    public delegate void AchievementDelegate(Platform platform, int stCode, string errorMsg);

    public static SocialSettings settings;

    private static int registerNum = 0;
    private static Action registerFinishAction;

    private static Dictionary<Platform, bool> installStatus = new Dictionary<Platform, bool>();
    private static Dictionary<Platform, bool> shareStatus = new Dictionary<Platform, bool>();
    private static Dictionary<Platform, bool> leaderboardStatus = new Dictionary<Platform, bool>();
    private static Dictionary<Platform, bool> achievementStatus = new Dictionary<Platform, bool>();
    private static Dictionary<Platform, bool> realStatus = new Dictionary<Platform, bool>();

    static SocialManager()
    {
      settings = LoadSettings();
    }

    public static void BindAllow(List<Platform> include)
    {
        allow = include;
    }

    public static void Bind(LogoutDelegate logoutDelegate)
    {
#if UNITY_ANDROID && !UNITY_EDITOR
			try
            {
                Run(delegate
                {
                    var androidCallbackListener = new AndroidCallbackListener(logoutDelegate);
                    CommonAd.AdSDK.CallStatic("bindCallback", androidCallbackListener);
                });
            }
            catch (AndroidJavaException exp)
            {
                LogTools.Error(exp.Message);
            }
#endif
    }

    public static void Init(Action callback,bool force = false)
    {
      if (registerNum > 0 && !force)
      {
        throw new Exception("Social already init");
      }

      registerNum = 0;
      if (settings == null)
      {
        callback();
        return;
      }
      registerFinishAction = callback;
      if ((allow==null || (allow != null && allow.Contains(Platform.Wechat))) && !String.IsNullOrEmpty(settings.WechatAppKey))
      {
        // 注册微信
        Register(Platform.Wechat, settings.WechatAppKey);
      }
      if ((allow==null || (allow != null && allow.Contains(Platform.Facebook))) && !String.IsNullOrEmpty(settings.FacebookAppKey))
      {
        // 注册Facebook
        Register(Platform.Facebook, settings.FacebookAppKey);
      }
      if ((allow==null || (allow != null && allow.Contains(Platform.TapCn))) && !String.IsNullOrEmpty(TapTap.TapTap.settings.ClientId))
      {
          // 注册Taptap
          RegisterHandler(Platform.TapCn, true, true, true, true, true);
          TapTap.TapTap.NeedInit = true;
          localPlatformAuth[Platform.TapCn] = TapTap.User.Auth(Platform.TapCn);
      }
      if ((allow==null || (allow != null && allow.Contains(Platform.TapIo))) && !String.IsNullOrEmpty(TapTap.TapTap.settings.ClientId))
      {
          // 注册Taptap
          RegisterHandler(Platform.TapIo, true, false, true, true, true);
          TapTap.TapTap.NeedInit = true;
          localPlatformAuth[Platform.TapIo] = TapTap.User.Auth(Platform.TapIo);
      }
      if ((allow==null || (allow != null && allow.Contains(Platform.Steam))) && Steam.Steam.In)
      {
          // 注册Steam
          RegisterHandler(Platform.Steam, true, false, true, true, false);
          localPlatformAuth[Platform.Steam] = Steam.User.Auth();
      }
      if ((allow==null || (allow != null && allow.Contains(Platform.Token))))
      {
          RegisterHandler(Platform.Token, true, false, false, false, false);
      }
#if UNITY_IOS && !UNITY_EDITOR
            if ((allow==null || (allow != null && allow.Contains(Platform.GameCenter))) && settings.GameCenter)
            {
                // 注册GameCenter
                Register(Platform.GameCenter, "");
            }
#endif
#if UNITY_ANDROID && !UNITY_EDITOR
            if ((allow==null || (allow != null && allow.Contains(Platform.GooglePlay))) && !String.IsNullOrEmpty(settings.GoogleAppId))
            {
                // 注册GooglePlay
                Register(Platform.GooglePlay, settings.GoogleAppId);
            }
#endif
      if (registerNum == 0)
      {
        // 无需要初始化的平台
        callback();
      }
    }
    private static SocialSettings LoadSettings()
    {
      SocialSettings loadedSettings = (SocialSettings)Resources.Load("SocialSettings", typeof(SocialSettings));
      if (loadedSettings == null)
      {
        loadedSettings = ScriptableObject.CreateInstance<SocialSettings>();
        LogTools.Error("SocialSettings is not exist (Resources)");
      }
      return loadedSettings;
    }

    internal static void SaveLocal(Platform p, Dictionary<string, string> message)
    {
        localPlayer = new Player();
        localPlayer.Platform = p;
        localPlayer.message = message;
    }
    
    public static void SilenceLogin(Platform p, Action<Dictionary<string, string>> success, Action fail)
    {
        if (!IsInstall(p))
        {
            if (fail!=null) fail();
            return;
        }
        IsAuthorized(p, (platform, code, message) =>
        {
            LogTools.Log("authorized: {0}, {1}, {2}", platform, code, message);
            AnalyticsManager.Event("authorized", new Dictionary<string, object>{{"platform", platform}, {"code", code}});
            if (code == SocialManager.SUCCESS)
            {
                SaveLocal(p, message);
                if (success != null) success(message);
            }
            else
            {
                LogTools.Error("authorized: fail {0}", fail);
                if (fail != null) fail();
            }
        });
    }

    public static void Logout(Platform platform, LogoutDelegate callback)
    {
        if (!IsInstall(platform))
        {
            if (callback!=null) callback(platform);
            return;
        }
        
        if (localPlatformAuth.TryGetValue(platform, out var value))
        {
            value.Logout(callback);
            return;
        }
#if UNITY_ANDROID && !UNITY_EDITOR
            try
            {
                Run(delegate
                {
                    var androidLogoutListener = new AndroidLogoutListener(callback);
                    SocialSDK.CallStatic("logout", (int) platform, androidLogoutListener);
                });
            }
            catch (AndroidJavaException exp)
            {
                LogTools.Error(exp.Message);
            }

#elif UNITY_IOS && !UNITY_EDITOR
            logoutDelegate = callback;
            logoutPlatform((int)platform, LogoutCallback);
#endif
    }
    public static void RegisterHandler(Platform platform, bool isInstall, bool isShared, bool isLeaderboard, bool isAchievement, bool isReal)
    {
        LogTools.Log("Social register:{0},{1},{2},{3},{4},{5}",platform,isInstall,isShared,isLeaderboard, isAchievement, isReal);
      installStatus[platform] = isInstall;
      shareStatus[platform] = isShared;
      leaderboardStatus[platform] = isLeaderboard;
      achievementStatus[platform] = isAchievement;
      realStatus[platform] = isReal;
      if (installStatus.Count == registerNum)
      {
        if (registerFinishAction != null)
        {
          registerFinishAction();
        }
      }
    }

    public static bool CanAuth(Platform platform)
    {
        return IsInstall(platform) && AuthTypePlatform.ContainsKey(platform);
    }

    public static bool IsInstall(Platform platform)
    {
      bool result = false;
      installStatus.TryGetValue(platform, out result);
      LogTools.Log("social is install: {0}, {1}", platform, result);
      return result;
    }

    public static bool IsShare(Platform platform)
    {
      bool result = false;
      shareStatus.TryGetValue(platform, out result);
      return result;
    }

    public static bool IsLeaderboard(Platform platform)
    {
        bool result = false;
        leaderboardStatus.TryGetValue(platform, out result);
        return result;
    }

    public static bool IsAchievement(Platform platform)
    {
        bool result = false;
        achievementStatus.TryGetValue(platform, out result);
        return result;
    }

    public static bool IsReal(Platform platform)
    {
        bool result = false;
        realStatus.TryGetValue(platform, out result);
        return result;
    }

    public static void Register(Platform platform, String appId)
    {
#if UNITY_ANDROID && !UNITY_EDITOR
            registerNum += 1;
            try
            {
                Run(delegate
                {
                    var androidRegisterListener = new AndroidRegisterListener(RegisterHandler);
                    SocialSDK.CallStatic("register", (int) platform, appId, androidRegisterListener);
                });
            }
            catch (AndroidJavaException exp)
            {
                LogTools.Error(exp.Message);
            }

#elif UNITY_IOS && !UNITY_EDITOR
            registerNum += 1;
            registerDelegate = RegisterHandler;
            registerPlatform((int)platform, appId, RegisterCallback);
#endif
    }

    public static void IsAuthorized(Platform platform, AuthDelegate callback)
    {
        if (!IsInstall(platform))
        {
            callback(platform, 0, new Dictionary<string, string>());
            return;
        }

        if (localPlatformAuth.TryGetValue(platform, out var value))
        {
            value.IsAuthorized(callback);
            return;
        }
#if UNITY_ANDROID && !UNITY_EDITOR
            try
            {
                Run(delegate
                {
                    var androidAuthListener = new AndroidAuthListener(callback);
                    SocialSDK.CallStatic("isAuthorized", (int) platform, androidAuthListener);
                });
            }
            catch (AndroidJavaException exp)
            {
                LogTools.Error(exp.Message);
            }

#elif UNITY_IOS && !UNITY_EDITOR
            authDelegate = callback;
            isAuthorized((int)platform, AuthCallback);
#endif
    }

    //授权某社交平台
    //platform 平台名 callback 授权成功完成
    public static void Authorize(Platform platform, AuthDelegate callback)
    {
        if (!IsInstall(platform))
        {
            callback(platform, 0, new Dictionary<string, string>());
            return;
        }
        
        AnalyticsManager.Event("authorize", new Dictionary<string, object>{{"platform", platform}});
        
        if (localPlatformAuth.TryGetValue(platform, out var value))
        {
            LogTools.Log("local platform auth");
            value.Authorize(callback);
            return;
        }
#if UNITY_ANDROID && !UNITY_EDITOR
            try
            {
                Run(delegate
                {
                    var androidAuthListener = new AndroidAuthListener(callback);
                    SocialSDK.CallStatic("authorize", (int) platform, androidAuthListener);
                });
            }
            catch (AndroidJavaException exp)
            {
                LogTools.Error(exp.Message);
            }

#elif UNITY_IOS && !UNITY_EDITOR
            authDelegate = callback;
            authorize((int)platform, AuthCallback);
#endif
    }

    public static void Real(Platform platform, RealDelegate callback)
    {
        if (!IsInstall(platform))
        {
            return;
        }

        if (!IsReal(platform))
        {
            return;
        }
        if (localPlatformAuth.TryGetValue(platform, out var value))
        {
            value.Real(callback);
            return;
        }
#if UNITY_ANDROID && !UNITY_EDITOR
            try
            {
                Run(delegate
                {
                    var androidRealListener = new AndroidRealListener(callback);
                    SocialSDK.CallStatic("real", (int) platform, androidRealListener);
                });
            }
            catch (AndroidJavaException exp)
            {
                LogTools.Error(exp.Message);
            }

#elif UNITY_IOS && !UNITY_EDITOR
            realDelegate = callback;
            real((int)platform, RealCallback);
#endif      
    }

    public static void UpdateData(Dictionary<string, string> info, Platform platform)
    {
        if (!IsInstall(platform))
        {
            return;
        }
        string keys = "";
        string values = "" ;
        int i = 0;
        var k = info.Keys.GetEnumerator();
        while (k.MoveNext())
        {
            i++;

            keys = keys+k.Current;
            if (i<=(info.Keys.Count-1)) {
                keys=keys+",";
            }
        }
        k.Dispose();
        int j = 0;
        var v = info.Values.GetEnumerator();
        while(v.MoveNext()) {
            j++;
            var vv = v.Current;
            if (vv == null){
                vv = "null";
            }else if (vv.Contains(",")){
                vv = vv.Replace(","," ");
            }
            values = values+vv;
            if (j<=(info.Values.Count-1)) {
                values=values+",";
            }
        }
        v.Dispose();
#if UNITY_ANDROID && !UNITY_EDITOR
            try
            {
                Run(delegate
                {
                    SocialSDK.CallStatic("updateData", (int) platform, keys, values);
                });
            }
            catch (AndroidJavaException exp)
            {
                LogTools.Error(exp.Message);
            }

#elif UNITY_IOS && !UNITY_EDITOR
            updateData((int)platform, keys, values);
#endif 
    }

    public static void SubmitLeaderboard(string key, int value, Platform platform, LeaderboardDelegate callback)
    {
        if (!IsInstall(platform))
        {
            callback(platform, 0, "no install");
            return;
        }

        if (!IsLeaderboard(platform))
        {
            callback(platform, 0, "no support");
            return;
        }
        if (localPlatformAuth.TryGetValue(platform, out var v))
        {
            v.SubmitLeaderboard(key, value, callback);
            return;
        }
#if UNITY_ANDROID && !UNITY_EDITOR
            try
            {
                Run(delegate
                {
                    var androidLeaderboardListener = new AndroidLeaderboardListener(callback);
                    SocialSDK.CallStatic("submitLeaderboard", (int) platform, key, value, androidLeaderboardListener);
                });
            }
            catch (AndroidJavaException exp)
            {
                LogTools.Error(exp.Message);
            }

#elif UNITY_IOS && !UNITY_EDITOR
            leaderboardDelegate = callback;
            submitLeaderboard((int)platform, key, value, LeaderbaordCallback);
#endif      
    }

    public static void AddAchievement(string key, int value, Platform platform, AchievementDelegate callback)
    {
        if (!IsInstall(platform))
        {
            callback(platform, 0, "no install");
            return;
        }

        if (!IsAchievement(platform))
        {
            callback(platform, 0, "no support");
            return;
        }
        if (localPlatformAuth.TryGetValue(platform, out var v))
        {
            v.AddAchievement(key, value, callback);
            return;
        }
#if UNITY_ANDROID && !UNITY_EDITOR
            try
            {
                Run(delegate
                {
                    var androidAchievementListener = new AndroidAchievementListener(callback);
                    SocialSDK.CallStatic("addAchievement", (int) platform, key, value, androidAchievementListener);
                });
            }
            catch (AndroidJavaException exp)
            {
                LogTools.Error(exp.Message);
            }

#elif UNITY_IOS && !UNITY_EDITOR
            achievementDelegate = callback;
            addAchievement((int)platform, key, value, AchievementCallback);
#endif
    }


    //直接分享到各个社交平台
    //platform 平台名，title 分享的文字，imagePath 分享的照片文件路径，callback 分享成功或失败的回调

    public static void DirectShare(Platform platform, string title, string imagePath, string description, string targetUrl,
        string videoUrl, ShareDelegate callback = null)
    {
        if (!IsInstall(platform))
        {
            callback(platform, 0, "no install");
            return;
        }

        if (!IsShare(platform))
        {
            callback(platform, 0, "no support");
            return;
        }
        if (localPlatformAuth.TryGetValue(platform, out var v))
        {
            if (v.CanLocalShare())
            {
                v.DirectShare(title, imagePath, description, targetUrl, videoUrl, callback);
                return;
            }
        }
        Debug.LogError($"platform share no local");
      try
      {
#if UNITY_ANDROID && !UNITY_EDITOR
          Debug.LogError($"{activity}");
                Run(delegate
                {
                    Debug.LogError($" activity run1");
                    var androidShareListener = new AndroidShareListener(callback);
                    Debug.LogError($" activity run2");
                    SocialSDK.CallStatic("directShare", (int)platform, title, imagePath, description, targetUrl, videoUrl, androidShareListener);
                    Debug.LogError($" activity run3");
                });

#elif UNITY_IOS && !UNITY_EDITOR
                shareDelegate = callback;
                directShare((int)platform, title, imagePath, description, targetUrl,videoUrl, ShareCallback);
#endif
      }
      catch (Exception e)
      {
          Debug.LogError($"{e}");
      }
    }


    //以下代码是内部实现
    //请勿修改

#if UNITY_ANDROID && !UNITY_EDITOR


        public delegate void Action();

        static void Run(Action action)
        {
        // Debug.LogError($"run action1");
            activity.Call("runOnUiThread", new AndroidJavaRunnable(action));
        // Debug.LogError($"run action2");
        }

        class AndroidCallbackListener : AndroidJavaProxy
        {
            public AndroidCallbackListener(LogoutDelegate logoutDelegate):base("com.ueffort.social.SocialCallbackListener")
            {
			    this.logoutDelegate = logoutDelegate;
            }

		    private LogoutDelegate logoutDelegate;

            public void OnLogout(int platform) {
			    LogTools.Log("OnPreloadAdSuccess .");
		    }
        }

        class AndroidRegisterListener : AndroidJavaProxy
        {
            public AndroidRegisterListener(RegisterDelegate Delegate):base("com.ueffort.social.SocialRegisterListener")
            {
                this.registerDelegate = Delegate;
            }

            private RegisterDelegate registerDelegate = null;

            public void onRegister(int platform, bool isInstall, bool isShared, bool isLeaderboard, bool isAchievement, bool isReal)
            {
                registerDelegate((Platform) platform, isInstall, isShared, isLeaderboard, isAchievement, isReal);
            }
        }

        class AndroidLogoutListener: AndroidJavaProxy
        {
            public AndroidLogoutListener(LogoutDelegate Delegate):base("com.ueffort.social.SocialLogoutListener")
            {
                this.logoutDelegate = Delegate;
            }

            private LogoutDelegate logoutDelegate = null;

            public void onLogout(int platform)
            {
                logoutDelegate((Platform) platform);
            }
        }

        class AndroidAuthListener : AndroidJavaProxy
        {
            public AndroidAuthListener(AuthDelegate Delegate)
                : base("com.ueffort.social.AuthListener")
            {
                this.authDelegate = Delegate;
            }

            AuthDelegate authDelegate = null;

            public void onAuth(int platform, int stCode, string key, string value)
            {
                LogTools.Log("xxxxxx stCode=" + stCode);
                string[] keys = key.Split(',');
                string[] values = value.Split(',');
                Dictionary<string, string> dic = new Dictionary<string, string>();
                //dic.Add (keys , values );
                for (int i = 0; i < keys.Length; i++)
                {
                    dic.Add(keys[i], values[i]);
                }

                LogTools.Log("xxxxxx length=" + values.Length);
                AnalyticsManager.Event("authorizeResult", new Dictionary<string, object>{{"platform", platform}});

                SaveLocal((Platform) platform, dic);
                authDelegate((Platform) platform, stCode, dic);
            }
        }

        class AndroidRealListener : AndroidJavaProxy
        {
            public AndroidRealListener(RealDelegate Delegate)
                : base("com.ueffort.social.RealListener")
            {
                this.realDelegate = Delegate;
            }

            RealDelegate realDelegate = null;

            public void onReal(int platform, int stCode, string errorMsg)
            {
                realDelegate((Platform) platform, stCode, errorMsg);
            }
        }

        class AndroidShareListener : AndroidJavaProxy
        {
            ShareDelegate shareDelegate = null;

            public AndroidShareListener(ShareDelegate Delegate)
                : base("com.ueffort.social.ShareListener")
            {
                this.shareDelegate = Delegate;
            }

            public void onShare(int platform, int stCode, string errorMsg)
            {
                shareDelegate((Platform) platform, stCode, errorMsg);
            }
        }

        class AndroidLeaderboardListener : AndroidJavaProxy
        {
            LeaderboardDelegate leaderboardDelegate = null;

            public AndroidLeaderboardListener(LeaderboardDelegate Delegate)
                : base("com.ueffort.social.LeaderboardListener")
            {
                this.leaderboardDelegate = Delegate;
            }

            public void onLeaderboard(int platform, int stCode, string errorMsg)
            {
                leaderboardDelegate((Platform) platform, stCode, errorMsg);
            }
        }

        class AndroidAchievementListener : AndroidJavaProxy
        {
            AchievementDelegate achievementDelegate = null;

            public AndroidAchievementListener(AchievementDelegate Delegate)
                : base("com.ueffort.social.AchievementListener")
            {
                this.achievementDelegate = Delegate;
            }

            public void onAchievement(int platform, int stCode, string errorMsg)
            {
                achievementDelegate((Platform) platform, stCode, errorMsg);
            }
        }


        static AndroidJavaClass SocialSDK = new AndroidJavaClass("com.ueffort.social.SocialSDK");


        static AndroidJavaObject activity =
            new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");


#elif UNITY_IOS && !UNITY_EDITOR

        static RegisterDelegate registerDelegate = null;

        static LogoutDelegate logoutDelegate = null;

        static AuthDelegate authDelegate = null;

        static RealDelegate realDelegate = null;

        static ShareDelegate shareDelegate = null;

        static LeaderboardDelegate leaderboardDelegate = null;

        static AchievementDelegate achievementDelegate = null;

        public delegate void AuthHandler(Platform platform, int stCode, string key, string value);

        [AOT.MonoPInvokeCallback(typeof(RegisterDelegate))]
        static void RegisterCallback(Platform platform, bool isInstall, bool isShared, bool isLeaderboard, bool isAchievement, bool isReal)
        {
            LogTools.Log("register: {0}, {1}, {2}", platform, isInstall, isShared, isLeaderboard, isAchievement, isReal);
            if (registerDelegate != null)
                registerDelegate(platform, isInstall, isShared, isLeaderboard, isAchievement, isReal);
        }

        [AOT.MonoPInvokeCallback(typeof(LogoutDelegate))]
        static void LogoutCallback(Platform platform)
        {
            LogTools.Log("logout: {0}", platform);
            if (logoutDelegate != null)
                logoutDelegate(platform);
        }

        [AOT.MonoPInvokeCallback(typeof(AuthHandler))]
        static void AuthCallback(Platform platform, int stCode, string key, string value)
        {
            LogTools.Log("xxxxxx stCode=" + stCode);
            string[] keys = key.Split(',');
            string[] values = value.Split(',');
            Dictionary<string, string> dic = new Dictionary<string, string>();
            //dic.Add (keys , values );
            for (int i = 0; i < keys.Length; i++)
            {
                dic.Add(keys[i], values[i]);
            }

            LogTools.Log("xxxxxx length=" + values.Length);

            AnalyticsManager.Event("authorizeResult", new Dictionary<string, object>{{"platform", platform}});
            SaveLocal(platform, dic);
            if (authDelegate != null)
                authDelegate(platform, stCode, dic);
        }

        [AOT.MonoPInvokeCallback(typeof(RealDelegate))]
        static void RealCallback(Platform platform, int stCode, string errorMsg)
        {
            if (realDelegate != null)
                realDelegate(platform, stCode, errorMsg);
        }

        [AOT.MonoPInvokeCallback(typeof(ShareDelegate))]
        static void ShareCallback(Platform platform, int stCode, string errorMsg)
        {
            if (shareDelegate != null)
                shareDelegate(platform, stCode, errorMsg);
        }

        [AOT.MonoPInvokeCallback(typeof(LeaderboardDelegate))]
        static void LeaderbaordCallback(Platform platform, int stCode, string errorMsg)
        {
            if (leaderboardDelegate != null)
                leaderboardDelegate(platform, stCode, errorMsg);
        }

        [AOT.MonoPInvokeCallback(typeof(AchievementDelegate))]
        static void AchievementCallback(Platform platform, int stCode, string errorMsg)
        {
            if (achievementDelegate != null)
                achievementDelegate(platform, stCode, errorMsg);
        }

        [DllImport("__Internal")]
        static extern void registerPlatform(int platform, string appId, RegisterDelegate callback);

        [DllImport("__Internal")]
        static extern void logoutPlatform(int platform, LogoutDelegate callback);

        [DllImport("__Internal")]
        static extern void authorize(int platform, AuthHandler callback);

        [DllImport("__Internal")]
        static extern void isAuthorized(int platform, AuthHandler callback);

        [DllImport("__Internal")]
        static extern void real(int platform, RealDelegate callback);

        [DllImport("__Internal")]
        static extern void directShare(int platform, string text, string imagePath, string title, string targeturl, string videourl,
            ShareDelegate callback);

        [DllImport("__Internal")]
        static extern void updateData(int platform, string key, string value);

        [DllImport("__Internal")]
        static extern void submitLeaderboard(int platform, string key, int value, LeaderboardDelegate callback);

        [DllImport("__Internal")]
        static extern void addAchievement(int platform, string text, int value, AchievementDelegate callback);
#endif
  }
}